﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.Events;

public class Explosion : MonoBehaviour {
    public float explosionRat=1;
    public float explosionRang=30;

    // setting
    public Transform PrefabToBoom =null;
    public uint numberOfObjects = 100;
    
    public float RotationRpm = 300f;
    public float RotationDamp = 100f;
    public float MinRotationRpm = 50f;

    public float Angle = 0;
    public bool RotateAutomatic = true;


    public static int randomSeed = 3467;

    // event system
    UnityEvent m_MyEvent;

    private List<Transform> prefabs = new List<Transform>();
    // Use this for initialization
    void Start () {
        createPrefabs();

        if (m_MyEvent == null)
            m_MyEvent = new UnityEvent();

        m_MyEvent.AddListener(SetExplosionAngle);
    }

	// Update is called once per frame
	void Update () {
        //Vector3 v = new Vector3(0, 0, 0);
        RotationRpm = RotationRpm - RotationDamp* Time.deltaTime;
        RotationRpm = Mathf.Max(RotationRpm, MinRotationRpm);

        if (RotateAutomatic)
        {
            float deltaAngle = Time.deltaTime * RotationRpm;
            Angle = Angle + deltaAngle;
            Angle = Angle % 360.0f;
        }
       
        Quaternion q = Quaternion.Euler(0, Angle, 0 );
		Random.InitState(randomSeed);
        for (int i = 0; i < prefabs.Count; i++)
        {
            Vector3 v = Random.insideUnitSphere;
            v = v * (explosionRang * explosionRat);
            v = q*v;
            Transform t = prefabs[i];
            t.position = v;
        }



    }
    void createPrefabs()
    {
        if (PrefabToBoom == null)
            return;
        prefabs.Clear();
		Random.InitState(randomSeed);
        for (int i = 0; i < numberOfObjects; i++)
        {
            
         
            Transform instante = (Transform) Instantiate(PrefabToBoom, new Vector3(0,0,0), Quaternion.identity);
            if (instante == null)
                break;
            instante.transform.parent = this.transform;
            prefabs.Add(instante);
        }
    }
    void SetExplosionAngle()
    {

    }
    void SetExplosionRange()
    {

    }
    
    public void SetExplosionColor(float value)
    {
        Material material = GetComponentInChildren<MeshRenderer>().sharedMaterial;
        material.color = Color.red * value;
    }
}
